class ActiveRecord::Base
  def self.reflection_foreign_key_map
    @reflection_foreign_key_map ||= reflections.inject({}) {|h, pair| field, reflection = pair; h[reflection.primary_key_name] = reflection; h}
  end
  
  def divine_label(table_name, value)
    (loaded_fixtures_for_model = Fixtures.all_loaded_fixtures[table_name]) &&
      (match = loaded_fixtures_for_model.find{ |label, fixture| fixture["id"].to_i == value }) &&
        match.first
  end
  
  def attribute_for_inspect_with_identify(attr_name)
    begin
      label = nil
      case
      when attr_name == "id"
        label = divine_label(self.class.table_name, self[attr_name])
      when reflection = self.class.reflection_foreign_key_map[attr_name]
        if reflection.options[:polymorphic]
          label = divine_label(self[reflection.options[:foreign_type]].constantize.table_name, self[attr_name])
        else
          label = divine_label(reflection.class_name.constantize.table_name, self[attr_name])
        end
      end
      label || attribute_for_inspect_without_identify(attr_name)
    rescue
      nil
    end
  end
  
  if method_defined?("attribute_for_inspect_without_identify")
    alias_method :attribute_for_inspect, :attribute_for_inspect_with_identify
  else
    alias_method_chain :attribute_for_inspect, :identify 
  end
end
